using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using Schedulr.Configuration;
using Schedulr.Helpers;
using Schedulr.Properties;
using Schedulr.Tools;

namespace Schedulr.Controls
{
    /// <summary>
    /// Allows the user to edit the application options.
    /// </summary>
    public partial class OptionsEditor : UserControl
    {
        #region Fields

        private Picture defaultPicture;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="OptionsEditor"/> class.
        /// </summary>
        public OptionsEditor()
        {
            InitializeComponent();
            Initialize();
        }

        #endregion

        #region Initialize & Save

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Initialize()
        {
            this.defaultPicture = new Picture();
            this.defaultPicture.PropertyChanged += delegate { UpdateSettings(); };
            this.defaultPictureEditor.SetPictures(new Picture[] { this.defaultPicture });
        }

        private void UpdateSettings()
        {
            // Get the selected set and group id's and persist them into the settings.
            Settings s = Settings.Default;
            Picture p = this.defaultPicture;
            s.DefaultDescription = p.Description;
            s.DefaultUploadWithNext = p.UploadWithNext;
            s.DefaultFamily = p.IsFamily;
            s.DefaultFriend = p.IsFriend;
            s.DefaultPublic = p.IsPublic;
            s.DefaultTags = p.Tags;
            s.DefaultTitle = p.Title;
            s.DefaultSets = Converter.ArrayToCollection(p.SetIds);
            s.DefaultGroups = Converter.ArrayToCollection(p.GroupIds);
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the Click event of the switchUserButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void switchUserButton_Click(object sender, EventArgs e)
        {
            using (UIActionScope scope = new UIActionScope("Switching user..."))
            {
                FlickrServer.SwitchUser();
            }
        }

        /// <summary>
        /// Handles the Click event of the openLogFileButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void openLogFileButton_Click(object sender, EventArgs e)
        {
            if (File.Exists(Logger.DefaultLogFilePath))
            {
                Process.Start(Logger.DefaultLogFilePath);
            }
        }

        /// <summary>
        /// Handles the Click event of the undoChangesButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void undoChangesButton_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this, "Are you sure you want to undo all your changes?", "Undo changes?", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                OnUndoChangesRequested(EventArgs.Empty);
            }
        }

        /// <summary>
        /// Handles the Click event of the exportConfigurationButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void exportConfigurationButton_Click(object sender, EventArgs e)
        {
            DialogResult result = this.exportConfigurationSaveFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                SchedulrConfiguration.Instance.Export(this.exportConfigurationSaveFileDialog.FileName);
            }
        }

        /// <summary>
        /// Handles the Click event of the importConfigurationButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void importConfigurationButton_Click(object sender, EventArgs e)
        {
            DialogResult result = this.importConfigurationOpenFileDialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                try
                {
                    SchedulrConfiguration.Instance.Import(this.importConfigurationOpenFileDialog.FileName);
                }
                catch (Exception)
                {
                    MessageBox.Show(this, string.Format(CultureInfo.CurrentCulture, "The specified configuration file could not be imported.{0}See the log file for more information.", Environment.NewLine), "Error importing configuration", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// Occurs when the user has requested to undo changes.
        /// </summary>
        public event EventHandler<EventArgs> UndoChangesRequested;

        /// <summary>
        /// Raises the <see cref="E:UndoChangesRequested"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void OnUndoChangesRequested(EventArgs e)
        {
            if (this.UndoChangesRequested != null)
            {
                this.UndoChangesRequested(this, e);
            }
        }

        #endregion
    }
}